package server;

import java.util.LinkedList;
import java.util.Queue;

import client.ClientCommLocale;

import communication.ClientComm;
import communication.ServerComm;


public class ServerClientCommLocaleStream implements ServerComm, Runnable {
	private ClientCommLocale client;
	private Server server;
	private boolean exiting;
	private Thread connThread;
	private Queue<String> queueToClient;
	private Queue<String> queueFromClient;
	
	public ServerClientCommLocaleStream(ClientCommLocale client, Server server, int num){
		this.client = client;
		this.server = server; 		
		exiting = false;
		client.setConnection(this);
		queueToClient = new LinkedList<String>();
		queueFromClient =  new LinkedList<String>();
		connThread = new Thread(this, ("ServerClient" + num));
		connThread.start();
	}
	
	@Override
	public synchronized void run(){
		while(!exiting){
			try {
				while (!queueFromClient.isEmpty())
					new MsgInterpreter(this, server, queueFromClient.poll());
				while (!queueToClient.isEmpty()){
					client.msgFromServer(queueToClient.poll());
				}
				wait();
			} catch(InterruptedException e){
				e.printStackTrace();
			} catch(NullPointerException e){}
		}
	}
	
	@Override
	public synchronized void msgFromClient(String msg){
		queueFromClient.offer(msg);
		notify();
	}
	@Override
	public synchronized void msgToClient(String msg){
		queueToClient.offer(msg);
		notify();
	}
	
	@Override
	public void cambioTurno(String msg) {}

	@Override
	public void connect(ClientComm cl) {}

	@Override
	public synchronized void close() {
		exiting = true;
		server.close();
	}

	@Override
	public void closeAll() {}
}
